package edu.nf.llmtest.service.impl;

import edu.nf.llmtest.common.VO.ResultVO;
import edu.nf.llmtest.common.enumeration.RedisKeyEnum;
import edu.nf.llmtest.service.MailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ Author bin
 * @ Create  2025/10/17 上午11:05
 * 邮件服务
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class MailServiceImpl implements MailService {
    /**
     * 邮箱客户端
     * */
    private final JavaMailSender mailSender;

    /**
     * redis缓存客户端
     * */
    private final StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 发送验证码给指定邮箱
     * @param email 邮箱
     * */
    public void sendVerifyCode(String email){
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
        //保存到redis缓存中 5分钟
        redisTemplate.opsForValue().set(RedisKeyEnum.LOGIN_CODE.getValue() + email, code, 5, TimeUnit.MINUTES);
        SimpleMailMessage message = new SimpleMailMessage();
        //这里用yml里面的
        message.setFrom(sender);
        message.setTo(email);
        message.setSubject("【AI旅行助手】邮箱登录验证码");
        message.setText("您的验证码是：" + code + "，有效期5分钟。请勿泄露。");
        mailSender.send(message);
    }

    /**
     * 验证码验证
     * @param email 邮箱
     * @param inputCode 输入的验证码
     * @return 验证结果
     * */
    public ResultVO verifyCode(String email, String inputCode) {
        String correct = redisTemplate.opsForValue().get(RedisKeyEnum.LOGIN_CODE.getValue() + email);
        if (correct == null)
            return new ResultVO(400, "验证码已过期", null);
        if (correct.equals(inputCode))
            return new ResultVO(200, "验证成功", null);
        else
            return new ResultVO(400, "验证码错误", null);
    }
}
